<?php
/**
 * alltosun.com qq授权 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
*/
class Action
{
    private $appid; // qq互联ID
    private $appkey; // qq互联key
    private $callback; // 回调地址
    private $password;
    private $hash;

    function __construct()
    {
        $openapi = Config::get('openapi');
        $this->appid = $openapi['qq'][0];
        $this->appkey = $openapi['qq'][1];
        $this->callback = $openapi['qq'][2];
        $this->hash = user_helper::random_hash(6);
        //echo $this->appid;
    }
    function __call($action = '', $param = array())
    {

    }

    /**
     * qq 授权页面加载
     */
    public function login()
    {
        $isBind = Request::Get('bind', '0');

        if(user_helper::get_user_id() && !$isBind) {
            return array('您已经登录过了。', 'error', AnUrl('user/setting'));
        }
        $_SESSION['state'] = md5(uniqid(rand(), TRUE));
        $login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
                .$this->appid. "&redirect_uri=" . urlencode($this->callback)
                . "&state=" . $_SESSION['state']
                . "&scope=get_user_info";
        $rfUrl = Request::Get('rfUrl', '');
        if($isBind) {
            $_SESSION['bind'] = $isBind;
            if(!user_helper::get_user_id()) {
                return array('您需要先登录才可以绑定第三方帐号。', 'error', AnUrl('user/login'));
            }
        } else {
            $_SESSION['bind'] = 0;
        }
        if(!isset($_SESSION['login_callback'])) {
            $_SESSION['login_callback'] = user_helper::get_jump_url($rfUrl);
        }
        Response::redirect($login_url);
    }

    /**
     * qq 授权回调方法
     */
    public function callback()
    {
        if ($_REQUEST['state'] == $_SESSION['state']) {
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                    . "client_id=" . $this->appid. "&redirect_uri=" . urlencode($this->callback)
                    . "&client_secret=" . $this->appkey. "&code=" . $_REQUEST["code"];

            $response = curl_request($token_url, 'get');
            if (strpos($response, "callback") !== false)
            {
                $lpos = strpos($response, "(");
                $rpos = strrpos($response, ")");
                $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
                $msg = json_decode($response, true);
                if (isset($msg['error'])) // 判断获取信息是否成功
                { // 失败原因.
                    return array("获取信息不正确【{$msg['error']}】", 'error', AnUrl('user/register'));
                }
            }
            //使用Access Token来获取用户的OpenID
            $params = array();
            parse_str($response, $params);
            $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
            $str  = curl_request($graph_url, 'get');
            if (strpos($str, "callback") !== false)
            {
                $lpos = strpos($str, "(");
                $rpos = strrpos($str, ")");
                $str  = substr($str, $lpos + 1, $rpos - $lpos -1);
            }
            $user = json_decode($str, true);
            if (isset($user['error'])) // 用户openid获取是否成功.
            {
                return array("获取信息不正确【{$msg['error']}】", 'error', AnUrl('user/register'));
            }
            //获取用户信息
            $user_info = self::get_user_info($params['access_token'],$this->appid, $user['openid']);
            $user_info['avatar'] = $user_info['figureurl_qq_2'];
            $user_info['user_name'] = $user_info['nickname'];
            if($user_info['msg']){ // 判断返回信息是否正确
                return array($user_info['msg'], 'error', AnUrl('user/login'));
            } else {
                $connect_info = _uri('connect_qq', array('connect_open_id'=>$user['openid']));
                if (!$connect_info) { // 录入授权信息
                    $connect_info = array(
                            'connect_open_id'        =>    $user['openid'],
                            'connect_site_id'        =>    5,
                            'connect_nick_name'      =>    $user_info['nickname'],
                            'access_token'   =>    $params['access_token'],
                            'refresh_token'  =>    $params['refresh_token'],
                            'expires_time'   =>    $params['expires_in']+time()
                    );
                    if($_SESSION['bind']) {
                        if(!user_helper::get_user_id()) {
                            return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                        }
                        $connect_info['user_id'] = user_helper::get_user_id();
                        $connect_id = _model('connect_qq')->create($connect_info);
                        if($connect_id) {
                            unset($_SESSION['bind']);
                            return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                        }
                    }
                    $connect_id = _model('connect_qq')->create($connect_info);
                    
                    $_SESSION['associatedConnectInfo']['id'] = $connect_id;
                    $_SESSION['associatedConnectInfo']['type'] = 'qq';
                    $_SESSION['associatedConnectInfo']['user_info'] = $user_info;
                    Response::redirect(AnUrl('openapi/choose_bind'));
                } else {

                    $connect_update_info = array(
                            'connect_nick_name'      =>    $user_info['nickname'],
                            'access_token'   =>    $params['access_token'],
                            'refresh_token'  =>    $params['refresh_token'],
                            'expires_time'   =>    $params['expires_in']+time()
                    );
                    _model('connect_qq')->update($connect_info['id'], $connect_update_info);

                    if(!$connect_info['user_id']) {
                        if($_SESSION['bind']) {
                            if(!user_helper::get_user_id()) {
                                return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                            }
                            $affected = _model('connect_qq')->update($connect_info['id'], array('user_id' => user_helper::get_user_id()));
                            if($affected) {
                                unset($_SESSION['bind']);
                                return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                            }
                        }
                        $_SESSION['associatedConnectInfo']['id'] = $connect_info['id'];
                        $_SESSION['associatedConnectInfo']['type'] = 'qq';
                        $_SESSION['associatedConnectInfo']['user_info'] = $user_info;
                        Response::redirect(AnUrl('openapi/choose_bind'));
                    } else {
                        if($_SESSION['bind']) {
                            unset($_SESSION['bind']);
                            return array('此QQ帐号已经被其他帐号绑定过了', 'error', AnUrl('user/setting/account_bind'));
                        }
                        $this->user_id = $connect_info['user_id'];
                        $db_user_info = _uri('user', $this->user_id);
                        $info = array(
                                'nickname'         =>    $user_info['nickname'],
                                'nickname_base64'  =>    base64_encode($user_info['nickname']),
                                'user_from'        =>     'qq',
                                'last_login_time'  =>    date('Y-m-d H:i:s', time())
                        );
                        if(empty($db_user_info['nickname'])) {
                            $info['nickname'] = $user_info['nickname'];
                        }
                        if(empty($db_user_info['avatar'])) {
                            $info['avatar'] = $user_info['figureurl_qq_2'];
                        }
                        _model('user')->update(array('id'=>$connect_info['user_id']), $info);
                        $return_info = $this->user_login($connect_info['user_id']);
                        if($return_info['info'] != 'error') {
                            echo $return_info;
                        } else {
                            return array($return_info['msg'], 'error', AnUrl('user/register'));
                        }
                    }                    
                }
            }
        } else {
            return array("验证信息过期【{$msg['error']}】", 'error', AnUrl('user/register'));
        }
    }

    private function user_login($user_id)
    {
        // 本站登录，写入session
        $user_info = _uri('user', $user_id);
        user_helper::session_update($user_info, 'qq');

        //同步登录ucenter
        $callback = $_SESSION['login_callback'];
        $return_info = user_helper::uc_login($user_info['uc_id'], '', $callback,0,1);
        return $return_info;
    }

    /**
     * 获取qq用户空间信息
     * @param str $access_token
     * @param str $openid
     * @return mixed
     */
    private function get_user_info($access_token, $app_id, $openid)
    {
        if (!$access_token) {
            return '用户未登录!';
        }

        $get_user_info = "https://graph.qq.com/user/get_user_info?"
                . "access_token=" . $access_token
                . "&oauth_consumer_key=" . $app_id
                . "&openid=" . $openid
                . "&format=json";
        $info = curl_request($get_user_info, 'get');
        $arr = json_decode($info, true);

        return $arr;
    }
}